﻿using System;
using System.Linq;
using System.Threading;
using SharedServiceLibrary;

namespace PumpStationServiceLibrary
{
    public class Simulator
    {
        private readonly Random _rand = new Random();
        private readonly PumpStation _pumpStation;
        private Thread _thread;
        private bool _running;

        public Simulator(PumpStation pumpStation)
        {
            _pumpStation = pumpStation;
            pumpStation.WaterLevel = WaterLevel.Normal;
        }

        public void Start()
        {
            _running = true;
            _thread = new Thread(Run);
            _thread.Start();
        }

        public void Stop()
        {
            _running = false;
            _thread.Join();
        }

        public void Run()
        {
            double total = 20.0;
            while (_running)
            {
                double flowps = _rand.NextDouble();
                double tcps = _pumpStation.Pumps.Where(pump => pump.Running).Sum(pump => pump.Capacity) / 60 / 60;
                total += flowps - tcps;
                if (total < 0.0)
                {
                    total = 0.0;
                    _pumpStation.WaterLevel = WaterLevel.Low;
                }
                else if (total > 40.0)
                {
                    total = 40.0;
                }

                if (total > 0.0)
                {
                    _pumpStation.WaterLevel = (WaterLevel) Math.Floor(total/10.0);
                }

                Thread.Sleep(1000);
            }
        }
    }
}